package cn.u313.lymusic.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import androidx.recyclerview.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import cn.u313.lymusic.R
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.common.AbsEntity
import com.arialyy.aria.core.download.DownloadEntity
import com.arialyy.aria.core.download.DownloadGroupEntity
import com.arialyy.aria.core.inf.IEntity
import com.arialyy.aria.core.wrapper.ITaskWrapper
import com.arialyy.aria.util.CommonUtil
import java.util.concurrent.ConcurrentHashMap


class MultiDownloadAdapter(val context: Context, private val data:ArrayList<DownloadEntity>) :
    BaseRecyclerViewAdapter<DownloadEntity, MultiDownloadAdapter.ListHolder>(context, data) {
    fun init(){
        mPositions.clear()
        for ((i, entity) in data.withIndex()) {
            mPositions[getKey(entity!!)] = i
        }
    }
    private val mPositions: ConcurrentHashMap<String, Int> = ConcurrentHashMap()
    override fun onCreateVH(parent: ViewGroup, viewType: Int): ListHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_download, parent, false)

        return ListHolder(view)
    }

    override fun onBindDataForItem(
        holder: ListHolder,
        position: Int,
        mData: MutableList<DownloadEntity>
    ) {
        val data = mData[position]
        var str = ""
        var color = android.R.color.holo_green_light
        when (data.getState()) {
            IEntity.STATE_WAIT -> str = "等待中"
            IEntity.STATE_OTHER, IEntity.STATE_FAIL -> str = "开始"
            IEntity.STATE_STOP -> {
                str = "恢复"
                color = android.R.color.holo_blue_light
            }
            IEntity.STATE_PRE, IEntity.STATE_POST_PRE, IEntity.STATE_RUNNING -> {
                str = "暂停"
                color = android.R.color.holo_red_light
            }
            IEntity.STATE_COMPLETE -> {
                str = "完成"
                holder.progress.progress = 100
            }
        }
        val size: Long = data.fileSize
        val progress: Long = data.currentProgress
        val current = if (size == 0L) 0 else (progress * 100 / size).toInt()
        holder.bt.text = str
        holder.bt.setTextColor(getColor(color))
        holder.progress.progress = current

        val listener = BtClickListener(data)
        holder.bt.setOnClickListener(listener)
        val name =
            if (isSimpleDownload(data)) (data as DownloadEntity).fileName else (data as DownloadGroupEntity).alias
        holder.name.text = "文件名：$name"
        holder.speed.text = data.convertSpeed
        holder.fileSize.text = covertCurrentSize(progress) + "/" + CommonUtil.formatFileSize(
            size.toDouble()
        )
        //删除按钮事件
        //删除按钮事件
        holder.cancel.setOnClickListener(View.OnClickListener {
            mData.remove(data)
            notifyDataSetChanged()
            cancel(data)
            //stop(entity);
        })
    }

    inner class ListHolder(view: View) : RecyclerView.ViewHolder(view) {
        val progress = itemView.findViewById<ProgressBar>(R.id.progressBar);
        val bt = itemView.findViewById<Button>(R.id.bt);
        val speed = itemView.findViewById<TextView>(R.id.speed);
        val fileSize = itemView.findViewById<TextView>(R.id.fileSize);
        val cancel = itemView.findViewById<TextView>(R.id.del);
        val name = itemView.findViewById<TextView>(R.id.name);
    }


    /**
     * 更新进度
     */
    @Synchronized
    fun setProgress(entity: DownloadEntity?) {
        if (entity == null) return
        val url = entity.key
        val position = indexItem(url)
        if (position == -1 || position >= mData.size) {
            return
        }
        mData[position] = entity
        notifyItemChanged(position, entity)
    }

    @Synchronized
    private fun indexItem(url: String): Int {
        val keys: Set<String> = mPositions.keys
        for (key in keys) {
            if (key == url) {
                return mPositions[key]!!
            }
        }
        return -1
    }
    @SuppressLint("NotifyDataSetChanged")
    @Synchronized
    fun updateState(entity: AbsEntity) {
//        YLog.e(entity)
        if (entity.state == IEntity.STATE_CANCEL || entity.state == IEntity.STATE_COMPLETE) {
            mData.remove(entity)
            mPositions.clear()
            for ((i, entity_1) in mData.withIndex()) {
                mPositions[getKey(entity_1)] = i
            }
            notifyDataSetChanged()
        } else {
            val position = indexItem(getKey(entity))
            if (position == -1 || position >= mData.size) {
                return
            }
            mData[position] = entity as DownloadEntity
            notifyItemChanged(position)
        }
    }
    private fun getKey(entity: AbsEntity): String {
        if (entity is DownloadEntity) {
            return entity.url
        } else if (entity is DownloadGroupEntity) {
            return entity.groupHash
        }
        return ""
    }
    private fun isSimpleDownload(entity: AbsEntity): Boolean {
        return entity is DownloadEntity
    }

    private fun covertCurrentSize(currentSize: Long): String? {
        return if (currentSize < 0) "0" else CommonUtil.formatFileSize(currentSize.toDouble())
    }

    private fun getColor(color: Int): Int {
        return Resources.getSystem().getColor(color)
    }

    private fun cancel(entity: AbsEntity) {
        when (entity.taskType) {
            ITaskWrapper.D_FTP -> Aria.download(getMContext())
                .loadFtp(entity.id) //.login("lao", "123456")
                .cancel(true)
            ITaskWrapper.D_FTP_DIR -> Aria.download(getMContext()).loadFtpDir(entity.id).cancel(true)
            ITaskWrapper.D_HTTP, ITaskWrapper.M3U8_VOD -> Aria.download(getMContext())
                .load(entity.id)
                .cancel(true)
            ITaskWrapper.DG_HTTP -> Aria.download(getMContext()).loadGroup(entity.id).cancel(true)
        }
    }

    private fun resume(entity: AbsEntity) {
        when (entity.taskType) {
            ITaskWrapper.D_FTP ->         //Aria.download(getMContext()).loadFtp((DownloadEntity) entity).login("lao", "123456").create();
                Aria.download(getMContext()).loadFtp(entity.id).resume(true)
            ITaskWrapper.D_FTP_DIR -> Aria.download(getMContext()).loadFtpDir(entity.id).resume(true)
            ITaskWrapper.D_HTTP, ITaskWrapper.M3U8_VOD -> Aria.download(getMContext())
                .load(entity.id).resume(true)
            ITaskWrapper.DG_HTTP -> Aria.download(getMContext()).loadGroup(entity.id).resume(true)
        }
    }

    private fun start(entity: AbsEntity) {
        when (entity.taskType) {
            ITaskWrapper.D_FTP ->         //Aria.download(getMContext()).loadFtp((DownloadEntity) entity).login("lao", "123456").create();
                Aria.download(getMContext()).loadFtp(entity.key).create()
            ITaskWrapper.D_FTP_DIR -> {}
            ITaskWrapper.D_HTTP, ITaskWrapper.M3U8_VOD -> Aria.download(getMContext())
                .load(entity.key).create()
            ITaskWrapper.DG_HTTP -> Aria.download(getMContext())
                .loadGroup((entity as DownloadGroupEntity).urls).create()
        }
    }

    private fun stop(entity: AbsEntity) {
//        if (!AppUtil.chekEntityValid(entity)) {
//            return
//        }
        when (entity.taskType) {
            ITaskWrapper.D_FTP -> Aria.download(getMContext()).loadFtp(entity.id).stop()
            ITaskWrapper.D_FTP_DIR -> {}
            ITaskWrapper.D_HTTP, ITaskWrapper.M3U8_VOD -> Aria.download(getMContext())
                .load(entity.id).stop()
            ITaskWrapper.DG_HTTP -> Aria.download(getMContext()).loadGroup(entity.id).stop()
        }
    }

    /**
     * 按钮事件
     */
    private inner class BtClickListener  constructor(private val entity: AbsEntity) :
        View.OnClickListener {
        override fun onClick(v: View) {
            when (entity.state) {
                IEntity.STATE_WAIT, IEntity.STATE_OTHER, IEntity.STATE_FAIL, IEntity.STATE_STOP, IEntity.STATE_PRE, IEntity.STATE_POST_PRE -> if (entity.id < 0) {
                    start(entity)
                } else {
                    resume(entity)
                }
                IEntity.STATE_RUNNING -> stop(entity)
                IEntity.STATE_COMPLETE -> Log.d(">>>>", "任务已完成")
            }
        }
    }
}